/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utn.resumiderobilletes.ui.forms;

import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import utn.resumiderobilletes.entidades.Categoria;
import utn.resumiderobilletes.entidades.Cuenta;
import utn.resumiderobilletes.entidades.Movimiento;
import utn.resumiderobilletes.listas.ListaGenerica;
import utn.resumiderobilletes.repositorios.Archivo;
import utn.resumiderobilletes.ui.modelos.ModeloCuentas;
import utn.resumiderobilletes.ui.modelos.ModeloMovimientos;

/**
 *
 * @author libanez
 */
public class FrmPrincipal extends javax.swing.JFrame {
    private Categoria mCatSelected;

    /**
     * Creates new form frmPrincipal
     */
    public FrmPrincipal() {
        initComponents();
        
        iniciarFormulario();
        
    }

    public void iniciarFormulario() {
        cargarCategorias();
        
        List<Movimiento> movimientos = Archivo.getDatos().getMovimientos().getTodos();
        setearGrilla(movimientos);
        
        List<Cuenta> cuentas = Archivo.getDatos().getCuentas().getTodos();
        seterGrillaCuentas(cuentas);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        treeCategorias = new javax.swing.JTree();
        txtCategoria = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableMovimientos = new javax.swing.JTable();
        btCuenta = new javax.swing.JButton();
        btMovimiento = new javax.swing.JButton();
        lblTotalCategorias = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblCuentas = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        lblCuentas = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        treeCategorias.setName(""); // NOI18N
        treeCategorias.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                treeCategoriasValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(treeCategorias);
        treeCategorias.getAccessibleContext().setAccessibleName("");

        txtCategoria.setToolTipText("");
        txtCategoria.setName("txtCategoria"); // NOI18N

        jLabel1.setText("Categorias");

        jButton1.setText("OK");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        tableMovimientos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(tableMovimientos);

        btCuenta.setText("Crear Cuenta");
        btCuenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCuentaActionPerformed(evt);
            }
        });

        btMovimiento.setText("Crear Movimiento");
        btMovimiento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btMovimientoActionPerformed(evt);
            }
        });

        lblTotalCategorias.setText("Total de categorias:");

        jLabel2.setText("Movimientos");

        tblCuentas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(tblCuentas);

        jLabel3.setText("Cuentas");

        lblCuentas.setText("jLabel4");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addComponent(txtCategoria)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButton1)))
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(lblTotalCategorias)))
                        .addGap(34, 34, 34)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(lblCuentas)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(156, 156, 156)
                        .addComponent(btCuenta)
                        .addGap(84, 84, 84)
                        .addComponent(btMovimiento)))
                .addContainerGap(98, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btCuenta)
                    .addComponent(btMovimiento))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblTotalCategorias)
                .addGap(20, 20, 20)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblCuentas)
                .addContainerGap(259, Short.MAX_VALUE))
        );

        jLabel1.getAccessibleContext().setAccessibleName("Nueva Categoria:");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        boolean result = false;
        if(!txtCategoria.getText().isEmpty()){             
             ListaGenerica<Categoria> lista = Archivo.getDatos().getCategorias();
             for (Categoria item : lista) {
                if (item.getDescripcion().equals(txtCategoria.getText())){
                    result = true;
                }
                 
             }
             if (result) {
                     JOptionPane.showMessageDialog(this, "La categoria no puede ser igual a otra.", "Error", JOptionPane.ERROR_MESSAGE);
                 }else{
                     Categoria cat = new Categoria(lista.getCantidad() + 1, txtCategoria.getText());
                     lista.agregar(cat);
                     txtCategoria.setText("");
                     cargarCategorias();
                 }
             
        }else{
             JOptionPane.showMessageDialog(this, "La categoria no puede ser vacia.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
                Archivo.guardar();
    }//GEN-LAST:event_formWindowClosing

    private void treeCategoriasValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_treeCategoriasValueChanged
                
        if (treeCategorias.getLastSelectedPathComponent()!= null && ((DefaultMutableTreeNode) treeCategorias.getLastSelectedPathComponent()).getUserObject() instanceof Categoria)
        {
            mCatSelected = (Categoria) ((DefaultMutableTreeNode) treeCategorias.getLastSelectedPathComponent()).getUserObject();
            setearGrilla(mCatSelected.getMovimientos());
        }
        else
        {
            mCatSelected = null;
            ListaGenerica<Movimiento> lista = Archivo.getDatos().getMovimientos();
            setearGrilla(lista.getTodos());
        }
    }//GEN-LAST:event_treeCategoriasValueChanged

    private void btCuentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCuentaActionPerformed
        FrmCuenta form = new FrmCuenta();
        form.setPadre(this);
        form.setVisible(true);
    }//GEN-LAST:event_btCuentaActionPerformed

    private void btMovimientoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMovimientoActionPerformed
       FrmMovimiento frmMovimiento = new FrmMovimiento();
       frmMovimiento.setPadre(this);
       frmMovimiento.setVisible(true);
    }//GEN-LAST:event_btMovimientoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmPrincipal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCuenta;
    private javax.swing.JButton btMovimiento;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblCuentas;
    private javax.swing.JLabel lblTotalCategorias;
    private javax.swing.JTable tableMovimientos;
    private javax.swing.JTable tblCuentas;
    private javax.swing.JTree treeCategorias;
    private javax.swing.JTextField txtCategoria;
    // End of variables declaration//GEN-END:variables

    public void cargarCategorias()
    {
        DefaultMutableTreeNode raiz = new DefaultMutableTreeNode();
        raiz.setUserObject("Todas");
        ListaGenerica<Categoria> lista = Archivo.getDatos().getCategorias();
        for (Categoria item : lista)
        {
            DefaultMutableTreeNode aux = new DefaultMutableTreeNode(item);
            raiz.add(aux);
        }        
        DefaultTreeModel modelo = new DefaultTreeModel(raiz);        
        treeCategorias.setModel(modelo);        
        lblTotalCategorias.setText("Total de categorias: " + lista.getCantidad());
    }
      
    private void setearGrilla(List<Movimiento> lista)
    {
        ModeloMovimientos model = new ModeloMovimientos(lista);
        tableMovimientos.setModel(model);

    }

    private void seterGrillaCuentas(List<Cuenta> cuentas) {
        ModeloCuentas mode = new ModeloCuentas(cuentas);
        tblCuentas.setModel(mode);
        lblCuentas.setText("Cantidad de Cuentas: " + cuentas.size());
    }
    
    
}
